// ignore_for_file: no_leading_underscores_for_local_identifiers

import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper_app/api/bocchi_gitee.dart';
import 'package:wallpaper_app/components/Images/image_list.dart';
import 'package:wallpaper_app/components/input/normal_input.dart';
import 'package:wallpaper_app/model/image_base.dart';

class BocchiPage extends StatefulWidget {
  const BocchiPage({super.key});

  @override
  State<BocchiPage> createState() => _BocchiPageState();
}

class _BocchiPageState extends State<BocchiPage> {
  List<ImageBase> imgs = [];
  List<ImageBase> imgOriginalList = [];
  bool isLoading = false;
  int page = 1;
  final int pageSize = 20;
  int totalPages = 0;

  // 筛选状态
  final TextEditingController controller = TextEditingController();
  String type = 'pc'; // 壁纸类型：pc/mobile
  String order = 'DESC'; // 排序方式：DESC(最新)/ASC(最早)
  String selectOrder = 'DESC';
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  // 初始化加载
  @override
  void initState() {
    super.initState();
    getBocchiImgs();
  }

  // 释放资源
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  Future<void> getBocchiImgs() async {
    if (!mounted || isLoading) return;
    setState(() {
      isLoading = true;
      imgOriginalList.clear();
      imgs.clear();
    });
    try {
      Response res = await getBocchiList(type: type);
      totalPages = res.data['totalPage'];
      List bocchi = res.data['list'];
      if (order == 'DESC') {
        for (var i = bocchi.length - 1; i >= 0; i--) {
          if (!bocchi[i]['tags'].toString().contains(controller.text)) continue;
          imgOriginalList.add(ImageBase(
            largePath: bocchi[i]['url'],
            smallPath: bocchi[i]['cover'],
            tags: bocchi[i]['tags'],
            width: bocchi[i]['width'],
            height: bocchi[i]['height'],
          ));
        }
      } else {
        for (var i = 0; i < bocchi.length; i++) {
          if (!bocchi[i]['tags'].toString().contains(controller.text)) continue;
          imgOriginalList.add(ImageBase(
            largePath: bocchi[i]['url'],
            smallPath: bocchi[i]['cover'],
            tags: bocchi[i]['tags'],
            width: bocchi[i]['width'],
            height: bocchi[i]['height'],
          ));
        }
      }
      setState(() {
        imgs = imgOriginalList.toList();
      });
    } catch (e) {
      debugPrint(e.toString());
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  void switchOrder(String newOrder) {
    if (selectOrder == 'ASC') {
      BotToast.showText(text: '最早');
    } else {
      BotToast.showText(text: '最新');
    }
    if (order == newOrder) return;
    setState(() {
      order = newOrder;
    });
    imgOriginalList = imgOriginalList.reversed.toList();
    _handleSearchSubmitted(controller.text);
  }

  // 处理搜索提交
  void _handleSearchSubmitted(String value) {
    setState(() {
      page = 1;
      imgs.clear();
      isLoading = true;
    });
    Future.delayed(const Duration(milliseconds: 300), () {
      setState(() {
        isLoading = false;
        //筛选出tags包含controller.text的图片
        imgs = imgOriginalList.where((element) {
          return element.tags.toString().contains(controller.text);
        }).toList();
      });
    });
  }

  Widget _buildSearchBar() {
    final theme = Theme.of(context).colorScheme;
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
      child: Row(
        children: [
          // 搜索输入框（占满剩余宽度）
          Expanded(
            child: NormalInput(
              controller: controller,
              radius: 12,
              height: 35,
              icon: const Icon(Icons.search, size: 20, color: Colors.grey),
              onSubmitted: _handleSearchSubmitted,
            ),
          ),
          _buildFilterButton(theme),
        ],
      ),
    );
  }

  /// 构建筛选按钮
  Widget _buildFilterButton(ColorScheme theme) {
    return Card(
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      child: Material(
        color: theme.primaryContainer,
        borderRadius: BorderRadius.circular(20),
        child: IconButton(
          icon: const Icon(Icons.filter_list, size: 22),
          padding: EdgeInsets.zero,
          constraints: const BoxConstraints(
            minWidth: 35,
            minHeight: 35,
            maxWidth: 35,
            maxHeight: 35,
          ),
          onPressed: () => _scaffoldKey.currentState?.openEndDrawer(),
          tooltip: '筛选类型与排序',
        ),
      ),
    );
  }

  /// 构建筛选抽屉（含类型筛选+排序筛选）
  Widget _buildFilterDrawer() {
    final theme = Theme.of(context).colorScheme;
    final textTheme = Theme.of(context).textTheme;

    return Drawer(
      backgroundColor: theme.surface,
      elevation: 8,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(0),
          bottomLeft: Radius.circular(0),
        ),
      ),
      child: Column(
        children: [
          // 抽屉头部
          _buildDrawerHeader(theme, textTheme),
          // 筛选内容（类型+排序）
          Expanded(
            child: ListView(
              padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
              children: [
                // 1. 壁纸类型筛选分组
                _buildDrawerGroupTitle('壁纸类型'),
                ..._buildTypeFilterItems(),
                const SizedBox(height: 20),
                // 2. 排序方式筛选分组
                _buildDrawerGroupTitle('排序方式'),
                ..._buildOrderFilterItems(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建抽屉头部
  Widget _buildDrawerHeader(ColorScheme theme, TextTheme textTheme) {
    return Container(
      padding: const EdgeInsets.all(16),
      color: theme.primaryContainer,
      child: Row(
        children: [
          const Icon(Icons.tune, size: 24),
          const SizedBox(width: 12),
          Text(
            '筛选与排序',
            style: textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.bold,
              color: theme.onPrimaryContainer,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建抽屉分组标题（如“壁纸类型”“排序方式”）
  Widget _buildDrawerGroupTitle(String title) {
    final textTheme = Theme.of(context).textTheme;
    return Row(
      spacing: 5,
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const SizedBox(width: 1),
        Container(
          width: 4,
          height: 14,
          decoration: BoxDecoration(
            color: Colors.blueAccent,
            borderRadius: BorderRadius.circular(5),
          ),
        ),
        Text(
          title,
          style: textTheme.labelLarge?.copyWith(
            fontWeight: FontWeight.bold,
            fontSize: 15,
          ),
        ),
      ],
    );
  }

  /// 构建壁纸类型筛选项
  List<Widget> _buildTypeFilterItems() {
    // 类型映射：值 → 显示文本+图标
    final typeMap = [
      {'value': 'pc', 'title': '电脑壁纸', 'icon': Icons.desktop_windows},
      {'value': 'mobile', 'title': '手机壁纸', 'icon': Icons.smartphone},
    ];

    return typeMap
        .map((item) => _buildDrawerOptionItem(
              icon: item['icon'] as IconData,
              title: item['title'] as String,
              isSelected: type == item['value'],
              onTap: () {
                setState(() => type = item['value'] as String);
                getBocchiImgs();
                Navigator.pop(context);
              },
            ))
        .toList();
  }

  /// 构建排序方式筛选项
  List<Widget> _buildOrderFilterItems() {
    // 排序映射：值 → 显示文本+图标
    final orderMap = [
      {'value': 'DESC', 'title': '最新优先', 'icon': Icons.access_time_outlined},
      {'value': 'ASC', 'title': '最早优先', 'icon': Icons.access_time_sharp},
    ];

    return orderMap
        .map((item) => _buildDrawerOptionItem(
              icon: item['icon'] as IconData,
              title: item['title'] as String,
              isSelected: selectOrder == item['value'],
              onTap: () {
                setState(() => selectOrder = item['value'] as String);
                switchOrder(item['value'] as String);
                Navigator.pop(context);
              },
            ))
        .toList();
  }

  /// 构建抽屉选项通用组件（复用类型/排序项）
  Widget _buildDrawerOptionItem({
    required IconData icon,
    required String title,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    final theme = Theme.of(context).colorScheme;
    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: Material(
        color: theme.primaryContainer,
        borderRadius: BorderRadius.circular(8),
        child: ListTile(
          leading: Icon(
            icon,
            color:
                isSelected ? theme.primary : theme.onSurface.withOpacity(0.7),
            size: 22,
          ),
          title: Text(
            title,
            style: TextStyle(
              color: isSelected ? theme.primary : theme.onSurface,
              fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
            ),
          ),
          trailing: isSelected
              ? Icon(Icons.check, color: theme.primary, size: 20)
              : null,
          onTap: onTap,
          selected: isSelected,
          selectedTileColor: theme.primaryContainer.withOpacity(0.2),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          contentPadding: const EdgeInsets.symmetric(horizontal: 16),
          minLeadingWidth: 24,
        ),
      ),
    );
  }

  /// 构建底部统计栏（类型+总数）
  Widget _buildBottomStatsBar() {
    final theme = Theme.of(context).colorScheme;
    final textTheme = Theme.of(context).textTheme;

    // 转换选中类型为显示文本
    String _getTypeText() {
      switch (type) {
        case 'pc':
          return '电脑壁纸';
        case 'mobile':
          return '手机壁纸';
        default:
          return '全部壁纸';
      }
    }

    // 转换排序方式为显示文本
    String _getOrderText() {
      return order == 'DESC' ? '最新优先' : '最早优先';
    }

    return Container(
      padding: const EdgeInsets.only(bottom: 6, left: 12, right: 12),
      decoration: BoxDecoration(
        color: theme.surface,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 2,
            spreadRadius: 1,
            offset: const Offset(0, -1),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '类型: ${_getTypeText()} | 排序: ${_getOrderText()}',
            style: textTheme.bodySmall?.copyWith(
              color: theme.onSurface.withOpacity(0.6),
            ),
          ),
          Text(
            '共 ${imgs.length} 张壁纸',
            style: textTheme.bodySmall?.copyWith(
              color: theme.onSurface.withOpacity(0.6),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Theme.of(context).colorScheme.surface,
      endDrawer: _buildFilterDrawer(), // 筛选抽屉（含排序）
      body: Column(
        children: [
          _buildSearchBar(), // 顶部搜索栏
          Expanded(
            // 壁纸列表（瀑布流）
            child: ImageList(
              imageList: imgs,
              addColumn: type == 'pc' ? 0 : 1,
              isLoading: isLoading,
              isWaterfallFlow: true,
              onImageBottomLoading: () {},
            ),
          ),
          _buildBottomStatsBar(), // 底部统计栏
        ],
      ),
    );
  }
}
